const fs = require('fs');
const log4js = require('./logUtils');
const logger = log4js.getLogger('utils');

const TAG = "[cacheUtils]";
module.exports = {
    /**
     * 在连的设备信息，并不一定与数据库同步,格式
     *  online:true,
     session:{realm:me.sipSetting.server_realm},
     version: sip版本号
     sumnum: 通道数
     password  : sip_command_password,
     deviceid  : deviceid,
     session   : {
          realm   : server_realm
        },
     sip_command_host  : uriObj.sip_command_host,
     sip_command_port  : uriObj.sip_command_port,
     play      : false, // 是否在播放
     uri       : uriObj.uri,
     last_heart:时间戳
     */
    registry: {
        invites: {}
    },
    // 把registry保存到文件
    save: function (callback) {
        let cache = [];
        // 删除invites信息
        if (this.registry.data) {
            delete this.registry.data['invites'];
        }

        let str = JSON.stringify(this.registry, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return;
                }
                cache.push(value);
            }
            return value;
        });
        fs.writeFile('./data/registry.data', str, callback);
    },
    // 从文件加载registry，就是上次程序关闭时的设置
    load: function () {
        let that = this;
        return new Promise(function (resolve, reject) {
            fs.readFile('./data/registry.data', (error, data) => {
                if (error) {
                    logger.error(TAG, "读取缓存文件出错", error);
                    that.registry = {};
                    reject();
                } else {
                    try {
                        that.registry = JSON.parse(data.toString());
                    }catch (e){
                        logger.error(TAG, "缓存文件反序列化异常", data.toString());
                        that.registry = {};
                    }
                    resolve(true);
                }
            });
        });

    }
};
